<template>
  <div class="external-service-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <!-- 加载动画或提示 -->
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error">加载失败：{{ error }}</div>

    <!-- 数据展示 -->
    <div v-else class="data-container">
      <!-- 视图区第一部分：查询表单区域 -->
      <div class="search-form-wrapper">
        <el-form :inline="true" :model="searchForm" :rules="searchFormRules" @keyup.enter="fetchListByButton"
          class="search-form" ref="searchFormRef">
          <!-- 默认展示查询条件区 -->
          <el-row type="flex" justify="start" align="middle" :gutter="20" class="search-form-row"
            style="margin-left: 0; margin-right: 0; flex-wrap: wrap">
            <el-col v-for="field in defaultDisplayQueryFileList" :key="field.queryAttributeName" :xs="24" :sm="24"
              :md="12" :lg="8" :xl="6" class="search-form-col"
              style="margin-bottom: 20px; padding-left: 0; padding-right: 0">
              <el-form-item :label="field.queryAttributeLabel" :prop="field.queryAttributeName" class="search-form-item"
                style="margin-bottom: 0; display: flex; align-items: center">
                <!-- 文本输入框 -->
                <el-input v-if="field.queryEditType === 'text'" v-model="searchForm[field.queryAttributeName]"
                  :placeholder="field.queryAttributePlaceholder" clearable style="width: 100%; min-width: 120px"
                  class="search-form-input"></el-input>


                <el-input v-if="field.queryEditType === 'number'" v-model="searchForm[field.queryAttributeName]"
                  :placeholder="field.queryAttributePlaceholder" clearable style="width: 100%; min-width: 120px"
                  class="search-form-input" @input="onNumberInput(field.queryAttributeName, /\D/g)"></el-input>

                <!-- 日期时间范围选择器 -->
                <el-date-picker v-else-if="field.queryEditType === 'datetime-range'"
                  v-model="dateRangeTemp[field.queryAttributeName]" type="datetimerange"
                  :placeholder="field.queryAttributePlaceholder"
                  @change="CommonFunctions.handleDateTimeRangeChange(dateRangeTemp, field.queryAttributeName, searchForm)"
                  clearable style="width: 100%; min-width: 330px; max-width: 100%" class="search-form-date-picker"
                  :shortcuts="CommonFunctions.dateRangeShortcuts">
                </el-date-picker>

                <!-- 下拉选择器 -->
                <el-select v-else-if="field.queryEditType === 'select'" v-model="searchForm[field.queryAttributeName]"
                  :placeholder="field.queryAttributePlaceholder" :multiple="!field.selectOperation?.isSingle"
                  :collapse-tags="!!field.selectOperation?.maxCollapseTags"
                  :max-collapse-tags="field.selectOperation?.maxCollapseTags || 3" clearable filterable
                  style="width: 240px" class="search-form-select">
                  <!-- option 渲染 -->
                  <el-option v-for="option in field.selectOperation?.options" :key="option.value" :label="option.label"
                    :value="option.value" :disabled="option.disabled"></el-option>

                  <!-- 插入尾部操作区域 -->
                  <template #footer>
                    <div style="
                        display: flex;
                        justify-content: flex-end;
                        gap: 6px;
                        padding: 4px 4px;
                      ">
                      <el-button text size="small" :disabled="(field.selectOperation?.options || []).every(
                        (opt) => opt.disabled
                      )
                        " @click="selectAllOptions(field)">全选</el-button>
                      <el-button text size="small" @click="clearAllOptions(field)">清空</el-button>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 默认隐藏查询条件区 -->
          <el-row v-if="isOpenHiddenSearchArea" :gutter="30">
            <el-row type="flex" justify="start" align="middle" :gutter="20" class="search-form-row"
              style="margin-left: 0; margin-right: 0; flex-wrap: wrap">
              <el-col v-for="field in defaultHiddenQueryFileList" :key="field.queryAttributeName" :xs="24" :sm="24"
                :md="12" :lg="8" :xl="6" class="search-form-col"
                style="margin-bottom: 16px; padding-left: 0; padding-right: 0">
                <el-form-item :label="field.queryAttributeLabel" :prop="field.queryAttributeName"
                  class="search-form-item" style="margin-bottom: 0; display: flex; align-items: center">
                  <!-- 文本输入框 -->
                  <el-input v-if="field.queryEditType === 'text'" v-model="searchForm[field.queryAttributeName]"
                    :placeholder="field.queryAttributePlaceholder" clearable style="width: 100%; min-width: 120px"
                    class="search-form-input"></el-input>



                  <!-- 下拉选择器 -->

                </el-form-item>
              </el-col>
            </el-row>

            <el-col :span="6">
              <el-form-item label="日期">
                <el-date-picker v-model="searchForm.date" type="date" placeholder="选择日期" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 视图区第二部分，全局按钮区域 -->
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item>
              <el-button type="danger" :disabled="selectedRows.length === 0"
                @click="handleBatchDeleteInComponent">批量删除</el-button>
              <el-button type="primary" @click="handleDownload" :disabled="isDownloading">
                <span v-if="!isDownloading">全量下载</span>
                <span v-else>下载中...</span>
              </el-button>
              <el-button type="primary" @click="handleCurrentPageDownloadInComponent">
                下载当前页
              </el-button>
              <el-button type="primary" @click="openAddDialog">
                新增
              </el-button>
              <el-button type="primary" @click="guiderColumnShowInVisibleColumnListDialog = true">选择列</el-button>
              <el-button class="toggle-btn" :class="{ hovered: isHovered }" @mouseenter="isHovered = true"
                @mouseleave="isHovered = false" @click="toggleAdvancedSearch">
                <span>{{ isOpenHiddenSearchArea ? "收起" : "展开" }}</span>
                <el-icon>
                  <ArrowUp v-if="isOpenHiddenSearchArea" />
                  <ArrowDown v-else />
                </el-icon>
              </el-button>
              <el-button @click="reset">重置</el-button>
              <el-button type="primary" @click="fetchListByButton">查询</el-button>
            </el-form-item>
          </el-col>

          <!-- 选择勾选展示列弹框 -->
          <el-dialog v-model="guiderColumnShowInVisibleColumnListDialog" title="选择列" width="30%" draggable>
            <el-checkbox-group v-model="visibleColumnList">
              <el-checkbox v-for="column in localTableColumnList" :key="column.attributeName"
                :label="column.attributeName" :disabled="column.extendsAttributeInfo.showRequired">
                {{ column.attributeLabel }}
                <span v-if="column.extendsAttributeInfo.showRequired" style="color: #f56c6c">（必选）</span>
              </el-checkbox>
            </el-checkbox-group>
            <template #footer>
              <el-button @click="selectAllColumns">选中所有列</el-button>
              <el-button @click="deselectAllColumns">清空所选列</el-button>
              <el-button @click="guiderColumnShowInVisibleColumnListDialog = false">确定</el-button>
            </template>
          </el-dialog>
        </el-row>
      </div>

      <!-- 视图区第三部分：表格区域 -->
      <div class="table-container">
        <el-table ref="tableRef" :data="sortedTableData" @sort-change="handleSortChange" :border="true"
          style="width: 100%; height: 450px" :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange" show-overflow-tooltip>
          <!-- 多选列 -->
          <el-table-column type="selection" width="55" />
          <el-table-column v-for="column in currentShowColumnList" :key="column.attributeName"
            :prop="column.returnDto ? `${column.returnDto}.${column.attributeName}` : column.attributeName"
            :label="column.attributeLabel" :width="column.extendsAttributeInfo.columnWidth"
            :align="column.extendsAttributeInfo.contentAlign" :sortable="column.isSortable"
            :formatter="column.extendsAttributeInfo.formatterFunction"
            :fixed="column.extendsAttributeInfo.fixedPosition">
            <template #header>
              <el-tooltip v-if="column.attributeTooltip" :content="column.attributeTooltip" placement="top">
                <span>{{ column.attributeLabel }}</span>
              </el-tooltip>
              <span v-else>{{ column.attributeLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="Operations" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleDetail(scope.row)">Detail</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
            :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @current-change="fetchListByPage" @size-change="fetchListByPage" />
        </div>
      </div>
    </div>
  </div>

  <el-dialog v-model="detailDialogShowFlag" title="详情信息" width="60%" draggable>
    <DetailDialog v-if="detailDialogShowFlag" :key="selectedRowId" :updateUri="updateUri" :detail-uri="detailUri"
      :row-id="selectedRowId" :row-data="selectedRowData" :table-column-list="localTableColumnList"
      :primaryKey="ViewConfig.primaryKey" :queryRequest="queryRequestFromConfig"
      @closeDialogEvent="detailDialogShowFlag = false" @updateTableRow="updateTableRowInList"></DetailDialog>
  </el-dialog>

  <el-dialog v-model="addDialogShowFlag" title="新增信息" width="60%" draggable>
    <AddDialog :add-url="ViewConfig.addUri" :table-column-list="localTableColumnList"
      @closeDialog="addDialogShowFlag = false" @addSuccess="fetchListByPage"></AddDialog>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, nextTick } from "vue";
import * as CommonFunctions from "@/views/common/ts/CommonFunction";
import { Params, SearchFormFieldDefinition } from "@/views/common/ts/Interface";
import { useTableSort } from "@/views/common/ts/Sort";
import { resetTableFormAndSort } from "@/views/common/ts/ResetUtils";
import DetailDialog from "@/views/common/view/DetailDialog.vue";
import AddDialog from "@/views/common/view/AddDialog.vue";
import {
  persistQueryConditions,
  type PersistenceParams
} from "@/views/common/ts/QueryPersistence";
import * as ViewConfig from "@/views/group/display-info/display-view-config";
import { filterInputByPattern } from '@/views/common/ts/EditFunction';
import axios from 'axios';

const localSearchFormConfig = ref<SearchFormFieldDefinition[]>([]);
const defaultDisplayQueryFileList = ref<SearchFormFieldDefinition[]>([]);
const defaultHiddenQueryFileList = ref<SearchFormFieldDefinition[]>([]);
const localTableColumnList = ViewConfig.tableColumnList;

let searchFormRules = ref({});

const displayInfoId = '1';
const userId = '1';
const queryName = 'DEFAULT';

// 页面初始化
onMounted(async () => {
  try {
    localSearchFormConfig.value = ViewConfig.searchFormConfig;
    const param = {
      queryDisplayInfoRequest: { displayInfoId: displayInfoId },
      userId: userId,
      queryName: queryName,
    };
    const res = await axios.post(
      '/web-display-server/displaySetting/selectDisplaySettingByUser',
      param
    );

    // 这里假设后端直接返回字段数组
    if (res && res.data) {
      localSearchFormConfig.value = JSON.parse(res.data.data);
    } else {
      alert(res.data.message);
    }

    searchFormRules = ref(CommonFunctions.generateRules(localSearchFormConfig.value));
    localSearchFormConfig.value.forEach((field) => {
      if (field.queryEditType === "select") {
        // 处理selectOperation为空的情况，默认为多选
        const selectOp = field.selectOperation || { isSingle: false, options: [] };
        const options = selectOp.options || [];
        const defaultValue = field.queryAttributeDefaultValue;

        // 单选场景（isSingle === true）
        if (selectOp.isSingle) {
          if (defaultValue) {
            // 1. 优先使用queryAttributeDefaultValue匹配
            const matchedByDefaultValue = options.find(
              opt => opt.value === defaultValue
            );
            searchForm.value[field.queryAttributeName] = matchedByDefaultValue ? matchedByDefaultValue.value : "";
          }
        }
        // 多选场景（isSingle === false）
        else {
          if (defaultValue) {
            // 1. 优先使用queryAttributeDefaultValue（已经是数组格式）
            const matchedByDefaultValue = options
              .filter(opt => defaultValue.includes(opt.value))
              .map(opt => opt.value);
            searchForm.value[field.queryAttributeName] = matchedByDefaultValue;
          }
        }
      }

      else if (field.queryEditType === "datetime-range") {
        // 初始化日期范围临时变量
        dateRangeTemp.value[field.queryAttributeName] = null;
        // 如果有默认值
        if (field.queryAttributeDefaultValue) {
          const [start, end] = field.queryAttributeDefaultValue.split(',');
          if (start && end) {
            const startDate = new Date(start);
            const endDate = new Date(end);
            // 如果日期有效
            if (!isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
              // 设置日期范围临时变量
              dateRangeTemp.value[field.queryAttributeName] = [startDate, endDate];
              // 使用 CommonFunction 中的方法来设置表单字段
              CommonFunctions.handleDateTimeRangeChange(
                dateRangeTemp.value, // 传递 .value
                field.queryAttributeName,
                searchForm.value
              );
            }
          }
        }
      }

      else {
        searchForm.value[field.queryAttributeName] =
          field.queryAttributeDefaultValue || "";
      }
    });


    defaultDisplayQueryFileList.value = localSearchFormConfig.value.filter(
      (field) => !field.isHidden
    );
    defaultHiddenQueryFileList.value = localSearchFormConfig.value.filter(
      (field) => field.isHidden
    );

    executeInitWhenFirstLoaded();
    // 设置表格引用
    setTableRef(tableRef.value);
  } catch (error) {
    console.error('加载 localSearchFormConfig 失败', error);
  }

});



// 添加 dateRangeTemp 响应式对象
const dateRangeTemp = ref<Record<string, [Date, Date] | null>>({});


const { loading, error, executeInitWhenFirstLoaded } = CommonFunctions.useInitialize();

// 使用排序hook
const { handleSortChange, createSortedData, resetSort, setTableRef, sortInfo } =
  useTableSort();

const detailDialogShowFlag = ref<boolean>(false);
const addDialogShowFlag = ref<boolean>(false);

// 表格引用
const tableRef = ref();

const searchForm = ref<Record<string, any>>({});

const onNumberInput = (key: string, pattern: RegExp) => {
  filterInputByPattern(searchForm.value, key, pattern);
};



// 用于动态记录每个select是否全选状态
const selectStatusMap = ref<Record<string, boolean>>({});
// 全选
const selectAllOptions = (field) => {
  const name = field.queryAttributeName;
  const options = field.selectOperation?.options || [];

  const enabledValues = options
    .filter((opt: { disabled: any }) => !opt.disabled)
    .map((opt) => opt.value);

  // 强制触发响应式
  searchForm.value = {
    ...searchForm.value,
    [name]: enabledValues,
  };

  selectStatusMap.value[name] = true;
};

// 清空
const clearAllOptions = (field) => {
  const name = field.queryAttributeName;
  searchForm.value[name] = [];
  selectStatusMap.value[name] = false;
};

// 表格显示列控制
const guiderColumnShowInVisibleColumnListDialog = ref(false);
const visibleColumnList = ref(CommonFunctions.getVisibleColumnList(localTableColumnList));
const currentShowColumnList = computed(() =>
  CommonFunctions.updateCurrentShowColumnListByVisibleList(
    localTableColumnList,
    visibleColumnList.value
  )
);

// 表格数据类型
type TableData = {
  [K in (typeof localTableColumnList)[number]["attributeName"]as K]: string;
};

const tableData = ref<TableData[]>([]);
const sortedTableData = createSortedData(tableData);

// 表格行选择
const selectedRows = ref<TableData[]>([]);
const handleSelectionChange = (rows: TableData[]) => {
  selectedRows.value = rows;
};

// 批量删除
const handleBatchDeleteInComponent = async () => {
  await CommonFunctions.handleBatchDelete(
    selectedRows.value,
    tableData,
    ViewConfig.primaryKey,
    total,
    ViewConfig.batchDeleteUri
  );
};

// 行操作
const selectedRowId = ref("");
const selectedRowData = ref<TableData | null>(null);
const handleDetail = (row: TableData) => {
  selectedRowId.value = row[ViewConfig.primaryKey];
  selectedRowData.value = row;
  // 这一步是关键，它保证了子组件接收到的是最新的 rowId 和 rowData
  nextTick(() => {
    detailDialogShowFlag.value = true;
  });
  detailDialogShowFlag.value = true;
};

// 分页相关
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const total = ref<number>(0);
const isOpenHiddenSearchArea = ref<boolean>(false);
const isHovered = ref<boolean>(false);

// 查询按钮
const searchFormRef = ref();
const fetchListUrl = ViewConfig.fetchListUri;
// 辅助函数，将驼峰命名转换为下划线命名
const camelToSnake = (str: string) => {
  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
};

const fetchListByPage = () => {
  const params: Params = {
    ...searchForm.value,
  };

  // 调用提取函数构建分页参数
  CommonFunctions.buildPaginationParams(params, currentPage.value, pageSize.value, false, ViewConfig.queryRequest);

  // 根据排序信息设置排序参数
  if (sortInfo.value.prop != null && sortInfo.value.order != null) {
    params.sortColumnName = camelToSnake(sortInfo.value.prop);
    params.descSort = sortInfo.value.order === "desc";
  }
  CommonFunctions.fetchList(searchFormRef, params, tableData, total, fetchListUrl, false, localSearchFormConfig.value);
};

const fetchListByButton = () => {
  currentPage.value = 1;
  const params: Params = {
    ...searchForm.value,
  };

  // 调用提取的函数构建分页参数
  CommonFunctions.buildPaginationParams(params, currentPage.value, pageSize.value, true, ViewConfig.queryRequest);

  // 根据排序信息设置排序参数
  if (sortInfo.value.prop != null && sortInfo.value.order != null) {
    params.sortColumnName = camelToSnake(sortInfo.value.prop);
    params.descSort = sortInfo.value.order === "desc";
  }

  CommonFunctions.fetchList(searchFormRef, params, tableData, total, fetchListUrl, true, localSearchFormConfig.value);

  // 查询条件持久化 - 新增功能
  const persistenceParams: PersistenceParams = {
    displayInfoId: displayInfoId,
    userId: userId,
    queryName: queryName,
    searchForm: searchForm.value,
    localSearchFormConfig: localSearchFormConfig.value
  };

  persistQueryConditions(persistenceParams, '/web-display-server/displaySetting/saveUserPageQueryInfo');


};


// 全量下载
const isDownloading = ref(false);
const handleDownload = async () => {
  try {
    isDownloading.value = true;
    const filteredParams = Object.fromEntries(
      Object.entries(searchForm.value).filter(
        ([, value]) => value !== null && value !== undefined && value !== ""
      )
    );
    // 类型声明
    const visableAttributeLabelMapList = ref<Array<Record<string, string>>>([]);
    // 构建
    visableAttributeLabelMapList.value = CommonFunctions.buildVisableAttributeLabelList(currentShowColumnList.value); // 现在返回的是 List<Map<String, String>>
    // 最终参数构建
    const params = {
      ...filteredParams,
      entityName: ViewConfig.entityName,
      attributeLabelMapList: JSON.stringify(visableAttributeLabelMapList.value), // 这是一个 List<Map<String, String>>
    };

    await CommonFunctions.handleCommonDownload(params, ViewConfig.downloadExcelUri);
  } catch (error) {
    console.error("下载失败:", error);
  } finally {
    isDownloading.value = false;
  }
};

// 当前页下载
const handleCurrentPageDownloadInComponent = () => {
  CommonFunctions.handleCurrentPageDownload(
    tableData.value,
    currentShowColumnList.value,
    searchForm.value, // 查询条件
    {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      total: total.value,
    }, // 分页信息
    "current_page_data"
  );
};

// 当前页下载
const openAddDialog = () => {
  addDialogShowFlag.value = true;
};

// 全选列
const selectAllColumns = () => {
  visibleColumnList.value = localTableColumnList
    .filter((column) => !column.extendsAttributeInfo.showRequired)
    .map((column) => column.attributeName);
};

// 全部取消列
const deselectAllColumns = () => {
  visibleColumnList.value = [];
};

// 其他功能
const toggleAdvancedSearch = () => {
  isOpenHiddenSearchArea.value = !isOpenHiddenSearchArea.value;
};

// 重置方法
const reset = () => {
  resetTableFormAndSort(searchForm, resetSort, tableRef);
  // 可选：重置后重新加载数据
  // 重置日期范围临时变量
  Object.keys(dateRangeTemp.value).forEach((key) => {
    dateRangeTemp.value[key] = null;
  });
};

// 在组件中定义需要传递的数据
const detailUri = ViewConfig.fetchDetailUri; // 你的详情接口URI
const updateUri = ViewConfig.updateUri; // 你的详情接口URI

// 表格行样式
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 1 ? "success-row" : "";
};

// 新增方法，用于更新表格数据中的某一行
const updateTableRowInList = (updatedRow: TableData) => {
  const primaryKey = ViewConfig.primaryKey;
  const index = tableData.value.findIndex(
    (row) => row[primaryKey] === updatedRow[primaryKey]
  );
  if (index !== -1) {
    tableData.value[index] = updatedRow;
    // 这里重新赋值触发响应式更新，使视图更新
    tableData.value = [...tableData.value];
  }
};
</script>

<style scoped>
@import "../../common/externalServicePage.scss";

::v-deep(.el-table.success-row) {
  background-color: #fdf6ec !important;
}
</style>